<template>
  <div class="material-product-container">
    <div class="header-section">
      <h2>产品物料管理</h2>
      <el-button type="primary" @click="handleAdd">新增</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-table
        v-loading="loading"
        :data="materialProductList"
        style="width: 100%"
        border
      >
        <!-- 修改表格字段名以匹配响应式数据 -->
        <el-table-column prop="productcode" label="编码" width="180" />
        <el-table-column prop="productName" label="名称" width="180" />
        <el-table-column prop="specifications" label="规格型号" />
        <el-table-column prop="unit" label="单位" width="100" />
        <el-table-column prop="earlywarningvalue" label="预警值" width="100" />
        <el-table-column prop="materialGroupName" label="所属群组" width="150" />
        <el-table-column prop="processrouteName" label="工艺路线" width="150" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.pageIndex"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        />
      </div>
    </div>

    <!-- 添加/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        label-width="100px"
      >
        <el-form-item label="编码" prop="productcode" :rules="[{ required: true, message: '请输入编码', trigger: 'blur' }]">
          <el-input v-model="formData.productcode" placeholder="请输入编码" />
        </el-form-item>
        <el-form-item label="名称" prop="productName" :rules="[{ required: true, message: '请输入名称', trigger: 'blur' }]">
          <el-input v-model="formData.productName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="规格型号" prop="specifications">
          <el-input v-model="formData.specifications" placeholder="请输入规格型号" />
        </el-form-item>
        <el-form-item label="单位" prop="unit" :rules="[{ required: true, message: '请选择单位', trigger: 'change' }]">
          <el-select v-model="formData.unit" placeholder="请选择单位">
            <el-option v-for="item in unitList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="预警值" prop="earlywarningvalue">
          <el-input v-model="formData.earlywarningvalue" placeholder="请输入预警值" />
        </el-form-item>
        <el-form-item label="群组类型" prop="grop" :rules="[{ required: true, message: '请选择群组类型', trigger: 'change' }]">
          <el-select v-model="formData.grop" placeholder="请选择群组类型" @change="onGroupTypeChange()">
            <el-option v-for="value in sourcegrop" :value="value.materialtypeid" :label="value.materialtypeName" ></el-option>
          </el-select>
     
        
        </el-form-item>
        <el-form-item label="群组" prop="grouptype" :rules="[{ required: true, message: '请选择群组', trigger: 'change' }]">
          <el-select v-model="formData.grouptype" placeholder="请选择群组" :disabled="!formData.grop">
            <el-option v-for="item in materialGroups"  :label="item.materialname" :value="item.materId" />
          </el-select>
        </el-form-item>
        <el-form-item label="工艺路线" prop="processroute" v-show="formData.grop==1||formData.grop==3" >
          <el-select v-model="formData.processroute" placeholder="请选择工艺路线" >
            <el-option v-for="item in processRoutes" :label="item.processrouteName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="describe">
          <el-input
            v-model="formData.describe"
            placeholder="请输入描述"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { APIs } from '../../Http/http'

// 表格数据
const materialProductList = ref<any[]>([])
const sourcegrop = ref<any[]>([])
// 分页数据
const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

// 恢复loading变量并用于数据加载状态管理
const loading = ref(false)

// 弹窗数据
const dialogVisible = ref(false)
const dialogTitle = ref('新增')
const formRef = ref()
const formData = reactive({
  "productcode": "",
  "productName": "",
  "specifications": "",
  "unit": "",
  "earlywarningvalue": null,
  "grouptype": null,
  "processroute": null,
  "describe": "",
  "createName": "",
  grop: null
})

// 下拉框数据
const materialGroups = ref<any[]>([])
const unitList = ref([
  { value: '个', label: '个' },
  { value: '件', label: '件' },
  { value: '套', label: '套' },
  { value: '箱', label: '箱' },
  { value: '包', label: '包' },
  { value: 'KG', label: 'KG' }
])
const processRoutes = ref<any[]>([])

// 获取物料群组列表 - 支持二级联动
// const getMaterialGroups = (materialTypeId?: number | string) => {
//   // 清空之前的物料群组数据
//   materialGroups.value = []
  
//   // 如果没有提供物料类型ID，不请求数据
//   if (!materialTypeId) {
//     return
//   }
  
//   // 使用用户提供的API路径和参数
//   APIs.get('/api/Read/GetMaterialGroupsWithType', { params: { Materialtypeid: materialTypeId } })
//     .then(res => {
//       if (res.data && res.data.data) {
//         materialGroups.value = res.data.data
//       }
//     })
//     .catch(error => {
//       console.error('获取物料群组失败:', error)
//       ElMessage.error('获取物料群组失败')
//     })
// }

const GropSele = () => {
  APIs.get('/api/Read/GetAllMaterialTypes').then(res => {
    sourcegrop.value = res.data.data
  })
}

// 获取工艺路线列表
const getProcessRoutes = () => {
  APIs.get('/api/Read/GetAllProcessRoutes').then(res => {
    if (res.data.data) {
      processRoutes.value = res.data.data
    }
  })
}

// 修复getMaterialProductList方法，添加loading状态管理
const getMaterialProductList = () => {
  loading.value = true
  console.log(formData)
  APIs.get('/api/Read/GetProductMaterialListWithJoins', { params: { Pageindex: pagination.pageIndex, PageSize: pagination.pageSize } })
    .then(res => {
      if (res.data && res.data.data) {
        materialProductList.value = res.data.data.data
        pagination.total = res.data.data.totalCount
      }
    })
    .finally(() => {
      loading.value = false
    })
}

const handleAdd = () => {
  dialogTitle.value = '新增'
  resetForm()
  dialogVisible.value = true
}

// 编辑物料产品
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑'

  Object.assign(formData, row)
  dialogVisible.value = true
}

// 删除物料产品
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除这条数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      APIs.post('/api/Write/DeleteProductMaterial',row)
        .then(() => {
          ElMessage.success('删除成功')
          getMaterialProductList()
        })
    })
}

// 表单提交
const handleSubmit = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      const isEdit = dialogTitle.value == '新增'
      const apiUrl = isEdit ? '/api/Write/AddProductMaterial' : '/api/Write/UpdateProductMaterial'
      APIs.post(apiUrl, formData)
        .then(() => {
          ElMessage.success(isEdit ? '添加成功' : '编辑成功')
          dialogVisible.value = false
          getMaterialProductList()
        })
        console.log(formData)
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    "productcode": "",
    "productName": "",
    "specifications": "",
    "unit": "",
    "earlywarningvalue": null,
    "grouptype": null,
    "processroute": null,
    "describe": "",
    "createName": "",
    grop: ""
  })
  
  // 清空物料群组数据
  materialGroups.value = []
}

// 监听分页变化 - 使用watch监听
watch(
  () => [pagination.pageIndex, pagination.pageSize],
  () => {
    getMaterialProductList()
  },
  { deep: true }
)

// 物料类型变化时的处理函数
const onGroupTypeChange = () => {
  APIs.get("/api/Read/GetMaterialGroupsWithType",{params:{Materialtypeid:formData.grop}}).then(res=>{
materialGroups.value=res.data.data
  })
}

// 初始化
onMounted(() => {
  GropSele()
  getProcessRoutes()
  getMaterialProductList()
})
</script>

<style scoped>
.material-product-container {
  padding: 20px;
  background: #fff;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-section h2 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.search-section {
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
}

.table-section {
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>